package com.lagou.edu.filter;

import com.lagou.edu.feign.UserClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private UserClient userClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();
        // user服务和code服务不交易token
        if (path.startsWith("/user") || path.startsWith("/code")) {
            return chain.filter(exchange);
        }

        // 检查token
        boolean isPermitted = true;
        HttpCookie cookie = request.getCookies().getFirst("token");
        if (cookie == null || StringUtils.isEmpty(cookie.getValue())) {
            isPermitted = false;
        }
        else {
            String token = cookie.getValue();
            String info = userClient.info(token);
            if ("false".equals(info)) {
                // token验证不通过
                isPermitted = false;
            }
        }

        if (!isPermitted) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            String respMsg = "无权限访问";
            DataBuffer wrap = response.bufferFactory().wrap(respMsg.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(wrap));
        }

        // token验证通过放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
